package com.jdjc.suject.domin.service.impl;

import com.jdjc.subject.common.enums.IsDeletedFlagEnum;
import com.jdjc.subject.infra.basic.entity.SubjectCategory;
import com.jdjc.subject.infra.basic.entity.SubjectLabel;
import com.jdjc.subject.infra.basic.entity.SubjectMapping;
import com.jdjc.subject.infra.basic.service.SubjectCategoryService;
import com.jdjc.subject.infra.basic.service.SubjectLabelService;
import com.jdjc.subject.infra.basic.service.SubjectMappingService;
import com.jdjc.suject.domin.convert.SubjectCatrgoryConverter;
import com.jdjc.suject.domin.entity.SubjectCategoryBO;
import com.jdjc.suject.domin.entity.SubjectLabelBO;
import com.jdjc.suject.domin.service.SubjectCategoryDomainService;
import com.jdjc.suject.domin.util.CacheUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService {
    @Resource
    private SubjectCategoryService subjectCategoryService;
    @Resource
    private SubjectMappingService subjectMappingService;
    @Resource
    private SubjectLabelService subjectLabelService;
    @Resource
    private ThreadPoolExecutor lableThreadPool;
    @Resource
    private CacheUtil cacheUtil;

    /**
     * 新增分类
     *
     * @param subjectCategoryBo
     */
    @Override
    public void add(SubjectCategoryBO subjectCategoryBo) {
        if (log.isInfoEnabled()) {
            log.info(" SubjectCategoryBO：add:BO:{}", subjectCategoryBo);
        }
        //接受一个 SubjectCategoryBO 类型的参数，并返回一个 SubjectCategory 类型的对象。
        SubjectCategory subjectCategory = SubjectCatrgoryConverter.INSTANCE.convertBOToCategory(subjectCategoryBo);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectCategoryService.insert(subjectCategory);
    }

    /**
     * 查询大类
     *
     * @return
     */
    @Override
    public List<SubjectCategoryBO> queryCategory(SubjectCategoryBO subjectCategoryBO) {
        //BO转换为SubjectCategory
        SubjectCategory subjectCategory = SubjectCatrgoryConverter.INSTANCE.convertBOToCategory(subjectCategoryBO);

        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBO> boList = SubjectCatrgoryConverter.INSTANCE.categoryListToBOList(subjectCategoryList);
        if (log.isInfoEnabled()) {
            log.info(" subjectCategoryList：queryPrimaryCategory：boList:{}", boList);
        }
        //查询每个分类题目数量
        boList.forEach(bo -> {
            Integer subjectCount = subjectCategoryService.querySubjectCount(bo.getId());
            bo.setCount(subjectCount);
        });
        return boList;
    }

    /**
     * 更新分类
     *
     * @param subjectCategoryBO
     * @return
     */
    @Override
    public Boolean updateCategory(SubjectCategoryBO subjectCategoryBO) {
        //BO转换为SubjectCategory
        SubjectCategory subjectCategory = SubjectCatrgoryConverter.INSTANCE.convertBOToCategory(subjectCategoryBO);
        int update = subjectCategoryService.update(subjectCategory);
        return update > 0;
    }

    /**
     * 删除分类
     *
     * @param subjectCategoryBO
     * @return
     */
    @Override
    public Boolean delete(SubjectCategoryBO subjectCategoryBO) {
        //BO转换为SubjectCategory
        SubjectCategory subjectCategory = SubjectCatrgoryConverter.INSTANCE.convertBOToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0;
    }

    /**
     * 查询分类及其标签
     *
     * @param subjectCategoryBO
     * @return
     */
    @SneakyThrows
    @Override
    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
        Long id = subjectCategoryBO.getId();
        // 创建一个缓存键，将字符串"categoryAndLabel."与subjectCategoryBO对象的ID拼接起来。
        String cacheKey = "categoryAndLabel." + id;
        // 尝试从本地缓存中获取与缓存键相关联的值。
        List<SubjectCategoryBO> result = cacheUtil.getResult(cacheKey, SubjectCategoryBO.class,
                (key) -> getSubjectCategoryBOS(id));
        //(key) -> getSubjectCategoryBOS(id)
        // Lambda表达式，表示一个函数，它接受一个参数key，并调用getSubjectCategoryBOS方法，将key作为参数传递给该方法
        return result;
    }

    /**
     * 抽取方法
     * 查询分类及其标签
     */
    private List<SubjectCategoryBO> getSubjectCategoryBOS(Long categoryId) {
        //查询当前大类下所有为删除的分类
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(categoryId);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        log.info("subjectCategoryList：queryCategoryAndLabel：subjectCategoryList:{}", subjectCategoryList);

        //获取分类下的标签信息
        List<SubjectCategoryBO> subjectCategoryBOList = SubjectCatrgoryConverter.INSTANCE.categoryListToBOList(subjectCategoryList);
        Map<Long, List<SubjectLabelBO>> map = new HashMap<>();
        // 使用lableThreadPool线程池异步执行getLabelBOList方法。
        List<CompletableFuture<Map<Long, List<SubjectLabelBO>>>> completableFutureList = subjectCategoryBOList.stream().map(categoryBO ->
                CompletableFuture.supplyAsync(() -> getLabelBOList(categoryBO), lableThreadPool)
        ).collect(Collectors.toList());

        // 遍历completableFutureList，等待每个异步任务完成，并将其结果添加到map中。
        completableFutureList.forEach(future -> {
            try {
                // 获取CompletableFuture的结果，这是一个Map<Long, List<SubjectLabelBO>>。
                Map<Long, List<SubjectLabelBO>> resultMap = future.get();
                // 将结果Map中的所有条目添加到map中。
                map.putAll(resultMap);
            } catch (Exception e) {
                // 如果当前线程在等待时被中断，则抛出RuntimeException。
                throw new RuntimeException(e);
            }
        });
        subjectCategoryBOList.forEach(categoryBO -> {
            // 使用categoryBO的ID从map中获取对应的SubjectLabelBO列表，并设置给categoryBO。
            categoryBO.setLabelBOList(map.get(categoryBO.getId()));
        });
         /*//定义所有的异步任务FutureTask的集合
        List<FutureTask<Map<Long, List<SubjectLabelBO>>>> futureTaskList = new LinkedList<>();
        Map<Long,List<SubjectLabelBO>> map = new HashMap<>();
        //线程池并发调用
        subjectCategoryBOList.forEach(category -> {
            FutureTask<Map<Long, List<SubjectLabelBO>>> futureTask = new FutureTask<>(() ->
                    getLabelBOList(category));
            Map<Long, List<SubjectLabelBO>> labelBOList = getLabelBOList(category);
            futureTaskList.add(futureTask);
            //提交给线程池执行
            lableThreadPool.submit(futureTask);
        });
        //遍历拿到的结果放入map
        for (FutureTask<Map<Long, List<SubjectLabelBO>>> futureTask : futureTaskList) {
            Map<Long,List<SubjectLabelBO>> resultMap=futureTask.get();
            if (CollectionUtils.isEmpty(resultMap)) {
                continue;
            }
            map.putAll(resultMap);
        }*/
        //遍历从map里拿到对应的标签信息
        return subjectCategoryBOList;
    }

    /**
     * 抽取出的方法，用于获取标签信息
     *
     * @param category
     * @return
     */
    private Map<Long, List<SubjectLabelBO>> getLabelBOList(SubjectCategoryBO category) {
        log.info("getLabelBOList:category:{}", category);
        Map<Long, List<SubjectLabelBO>> labelMap = new HashMap<>();
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(category.getId());
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        if (CollectionUtils.isEmpty(mappingList)) {
            return null;
        }
        //通过stream得到该分类的所有labelId集合
        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        //获取所有标签信息
        List<SubjectLabel> labelList = subjectLabelService.batchqueryById(labelIdList);

        List<SubjectLabelBO> labelBOList = new LinkedList<>();
        labelList.forEach(label -> {
            SubjectLabelBO subjectLabelBO = new SubjectLabelBO();
            subjectLabelBO.setId(label.getId());
            subjectLabelBO.setLabelName(label.getLabelName());
            subjectLabelBO.setCategoryId(Long.valueOf(label.getCategoryId()));
            subjectLabelBO.setSortNum(label.getSortNum());
            labelBOList.add(subjectLabelBO);
        });
        labelMap.put(category.getId(), labelBOList);
        return labelMap;
    }
}
